import React, {useEffect, useState} from 'react';
import {Edit2, Trash2, UserPlus, Users} from 'lucide-react';
import DeleteConfirmModal from '../../components/modals/DeleteConfirmModal';
import MedalManageModal from '../../components/modals/MedalManageModal';
import MedalUsersModal from '../../components/modals/MedalUsersModal';
import MedalGrantModal from '../../components/modals/MedalGrantModal';
import {Req} from '../../util/fetch';

interface Medal {
  id: number;
  name: string;
  icon: string;
  description: string;
  requirements: string;
  grantedUsers?: {
    id: number;
    name: string;
    avatar: string;
    department: string;
    grantedAt: string;
  }[];
}

export default function AdminMedals() {
  const [medals, setMedals] = useState<Medal[]>([]);
  const [showManageModal, setShowManageModal] = useState(false);
  const [showUsersModal, setShowUsersModal] = useState(false);
  const [showGrantModal, setShowGrantModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedMedal, setSelectedMedal] = useState<Medal | null>(null);
  const [modalMode, setModalMode] = useState<'add' | 'edit'>('add');

  const handleAddMedal = () => {
    setModalMode('add');
    setSelectedMedal(null);
    setShowManageModal(true);
  };

  const handleEditMedal = (medal: Medal) => {
    setModalMode('edit');
    setSelectedMedal(medal);
    setShowManageModal(true);
  };

  const handleViewUsers = (medal: Medal) => {
    setSelectedMedal(medal);
    setShowUsersModal(true);
  };

  const handleGrantMedal = (medal: Medal) => {
    setSelectedMedal(medal);
    setShowGrantModal(true);
  };

  const handleDeleteMedal = (medal: Medal) => {
    setSelectedMedal(medal);
    setShowDeleteModal(true);
  };

  const handleSaveMedal = async (medalData: any) => {
    let method = 'POST'
    let url = '/bsMedal/add'
    if (selectedMedal) {
      medalData.id = selectedMedal.id;
      method = 'PUT'
      url = '/bsMedal/edit'
    }
    const res = await Req(url, {
      method,
      body: medalData,
      headers: undefined
    })
    if (res.success) {
      await queryList()
      setShowManageModal(false);
      setSelectedMedal(null);
      alert(res.message)
    } else {
      alert(res.message)
    }
  };

  const handleConfirmDelete = async () => {
    if (selectedMedal) {
      const res = await Req('/bsMedal/batch?ids=' + selectedMedal.id, {
        method: 'DELETE',
        headers: undefined
      })
      if (res.success) {
        alert(res.message)
        await queryList()
        setShowDeleteModal(false);
        setSelectedMedal(null);
      } else {
        alert(res.message)
      }
    }
  };

  const handleGrantUsers = async (users: any[]) => {
    const res = await Req('/bsPersionMedal/add', {
      method: 'POST',
      body: {
        medalId: selectedMedal.id,
        list: users.map(item => {
          return {
            medalId: selectedMedal.id,
            personId: item.id,
          }
        }),
      },
      headers: undefined
    })
    if (res.success) {
      alert(res.message)
      await queryList()
      setShowGrantModal(false);
    } else {
      alert(res.message)
    }
  };

  const queryList = async () => {
    const res = await Req(`/bsMedal/list`)
    if (res.success) {
      setMedals(res.data)
    } else {
      alert(res.message)
    }
  };

  useEffect(() => {
    queryList()
  }, [])

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900">勋章管理</h1>
        <p className="text-gray-500">管理系统勋章和发放记录</p>
      </div>

      {/* 工具栏 */}
      <div className="flex justify-end mb-6">
        <button
          onClick={handleAddMedal}
          className="flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
        >
          <UserPlus className="w-5 h-5 mr-2" />
          添加勋章
        </button>
      </div>

      {/* 勋章列表 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {medals.map(medal => (
          <div
            key={medal.id}
            className="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-all duration-300"
          >
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center space-x-3">
                <div className="text-4xl">{medal.icon}</div>
                <div>
                  <h3 className="text-lg font-semibold text-gray-900">{medal.name}</h3>
                  <p className="text-sm text-gray-500">{medal.description}</p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => handleEditMedal(medal)}
                  className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                >
                  <Edit2 className="w-5 h-5" />
                </button>
                <button
                  onClick={() => handleDeleteMedal(medal)}
                  className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                >
                  <Trash2 className="w-5 h-5" />
                </button>
              </div>
            </div>

            <div className="space-y-4">
              <div className="bg-gray-50 rounded-lg p-4">
                <div className="text-sm text-gray-500 mb-2">获得条件</div>
                <p className="text-gray-700">{medal.requirements}</p>
              </div>

              <div className="flex justify-between items-center">
                <button
                    // onClick={() => handleViewUsers(medal)}
                  className="flex items-center text-gray-500 hover:text-blue-500"
                >
                  <Users className="w-5 h-5 mr-1" />
                  <span className="text-sm">
                    {medal.grantedUsers?.length || 0} 人获得
                  </span>
                </button>
                <button
                  onClick={() => handleGrantMedal(medal)}
                  className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                >
                  发放勋章
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 勋章管理模态框 */}
      {showManageModal && (
        <MedalManageModal
          mode={modalMode}
          medal={selectedMedal}
          onClose={() => {
            setShowManageModal(false);
            setSelectedMedal(null);
          }}
          onSave={handleSaveMedal}
        />
      )}

      {/* 获得者列表模态框 */}
      {showUsersModal && selectedMedal && (
        <MedalUsersModal
          medal={selectedMedal}
          onClose={() => {
            setShowUsersModal(false);
            setSelectedMedal(null);
          }}
        />
      )}

      {/* 发放勋章模态框 */}
      {showGrantModal && selectedMedal && (
        <MedalGrantModal
          medal={selectedMedal}
          onClose={() => {
            setShowGrantModal(false);
            setSelectedMedal(null);
          }}
          onSave={handleGrantUsers}
        />
      )}

      {/* 删除确认模态框 */}
      {showDeleteModal && selectedMedal && (
        <DeleteConfirmModal
          title="删除勋章"
          message={`确定要删除"${selectedMedal.name}"勋章吗？此操作不可恢复。`}
          onConfirm={handleConfirmDelete}
          onCancel={() => {
            setShowDeleteModal(false);
            setSelectedMedal(null);
          }}
        />
      )}
    </div>
  );
}